package org.wattdepot.simulation.dorm.main;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.simulation.dorm.floor.FloorLoad;
import org.wattdepot.simulation.dorm.floor.FloorLoadTimerTask;
import org.wattdepot.simulation.util.SimulationClient;

/**
 * The main program for the UH Dorm simulation.
 * @author Philip Johnson
 */
public class Simulation {
  
    /**
     * The main for the UH Dorm simulation. 
     * @param args Ignored.
     * @throws Exception If problems occur.
     */
    public static void main(String[] args) throws Exception {
      List<Timer> timers = new ArrayList<Timer>();
      try {
        System.out.println("UH Dorm simulation is now running. Press return to stop server.");
        for (FloorLoad floor : FloorLoad.values()) {
          WattDepotClient client = SimulationClient.getWattDepotDormClient();
          System.out.format("Initializing source %s with energy to date.%n", floor);
          floor.initializeEnergyConsumed(client);
          Timer timer = new Timer();
          timers.add(timer);
          TimerTask floorTask = new FloorLoadTimerTask(floor, client);
          long tenSeconds = 1000 * 10;
          timer.scheduleAtFixedRate(floorTask, new Date(), tenSeconds);
          // Pause a bit so that our timers do not all execute simultaneously.
          Thread.sleep(500);
        }
        // Now wait for keyboard input indicating that execution should terminate.
        while (System.in.available() == 0) {
          Thread.sleep(2000);
        }
        System.out.println("Stopping UH Dorm simulation.");
        // Exit gracefully.
        for (Timer timer : timers) {
          timer.cancel();
        }
      }
      catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
      }
    }
  }